//
//  AppDelegate.m
//  wifi4.2
//
//  Created by 郭四虎 on 15/11/9.
//  Copyright © 2015年 YouKu. All rights reserved.
//

#import "AppDelegate.h"
#import "BaseViewController.h"
#import "GuideViewController.h"
#import "LoginViewController.h"
#import "MyTabBarController.h"
#import "HomeDetailViewController.h"

#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>

#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import "WXApi.h"
#import "WeiboSDK.h"

#import "UMessage.h"

#define youmengkey @"56989fe467e58eabf1001978"

@interface AppDelegate ()
{
    NSDictionary *_userinfo;
}
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    //推送进入特定的界面
        NSDictionary* userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    
//        if (userInfo) {
//            HomeDetailViewController *detail = [[HomeDetailViewController alloc]init];
//            detail.urlstr = [userInfo objectForKey:@"url"];
//            UIViewController *vc = [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
//    
//            [vc.navigationController pushViewController:detail animated:YES];
//        }
    
    _isFull = NO;
    
    [self checkNet];
    [self registShareSDK];
    [self registUMeng:launchOptions];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    // self.window.rootViewController = [[GuideViewController alloc]init];
    
    //获取Mac
    [MyCar isBus:^(bool isbus) {
        NSLog(@"qqqqq%d",isbus);
        if (isbus) {
            [[NSUserDefaults standardUserDefaults]setObject:@(1) forKey:@"isbus"];
            
            //通网
            [self contactNet];
            
        }else
        {
            [[NSUserDefaults standardUserDefaults]setObject:@(0) forKey:@"isbus"];
        }
        
        
    }];
    
    if (![[NSUserDefaults standardUserDefaults]boolForKey:@"firstLunch"]) {
        [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"firstLunch"];
        
        [[NSUserDefaults standardUserDefaults]setObject:@(0) forKey:@"showad"];
        self.window.rootViewController = [[GuideViewController alloc]init];
    }else{
        
        
        [[NSUserDefaults standardUserDefaults]setObject:@(1) forKey:@"showad"];
        MyTabBarController *tab;
        if (!userInfo) {
            tab = [[MyTabBarController alloc]initWithDic:nil];
        }else{
            tab = [[MyTabBarController alloc]initWithBool:YES];
        }
        
        
        self.window.rootViewController = tab;
//        LoadAdController *load = [[LoadAdController alloc]init];
//        self.window.rootViewController = load;
    }
    
    [[UIBarButtonItem appearance]setTintColor:[UIColor blackColor]];
    
    [[UINavigationBar appearance] setBarTintColor:[UIColor whiteColor]];
    [[UITabBar appearance] setBarTintColor:[UIColor whiteColor]];
    //[[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:238/255.0 green:238/255.0 blue:238/255.0 alpha:1]];
    

    return YES;
}


- (void)contactNet
{
    //通网
    //[NSString stringWithFormat:@"%@index.php/Port/ltonUs",CAR_URL]
    
    if ([factory isEqualToString:@"TBS"]) {
        
        [MyAFN POST:@"http://192.168.84.1:2060/wifidog/auth?token=42dcdb7e52f72de203881cbcbb4a6b59" parameters:nil block:^(id responseObject) {
            
            [MyCar getMAC:^{
                
            }];
            
        } error:^(NSError *error) {
            
            NSLog(@"%@",error);
        } fromController:nil];
    }else{
        
        [MyAFN POST:@"http://c.com/ajaxApi.php" parameters:@{@"action":@"user_auth"} block:^(id responseObject) {
            
            
        } error:^(NSError *error) {
            
            NSLog(@"%@",error);
        } fromController:nil];
    }
}


- (void)registShareSDK
{
    [ShareSDK registerApp:@"c818f0517e90" activePlatforms:@[@(SSDKPlatformTypeSinaWeibo),@(SSDKPlatformTypeWechat),@(SSDKPlatformTypeQQ)] onImport:^(SSDKPlatformType platformType) {
        
        switch (platformType)
        
        {
                
            case SSDKPlatformTypeWechat:
                
                [ShareSDKConnector connectWeChat:[WXApi class]];
                
                break;
                
                
                
            case SSDKPlatformTypeQQ:
                [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                break;
                
                
            case SSDKPlatformTypeSinaWeibo:
                
                [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                
                break;
                
            default:
                
                break;
                
        }
        
    }
     onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo) {
         
         switch (platformType) {
             case SSDKPlatformTypeSinaWeibo:
                // @"http://www.iucool.cn"
                 [appInfo SSDKSetupSinaWeiboByAppKey:@"798891516" appSecret:@"c78b75a43b05867ad05b3c31667d7dfc" redirectUri:@"http://www.sharesdk.cn" authType:SSDKAuthTypeBoth];
                 
                 break;
             case SSDKPlatformTypeWechat:
                 [appInfo SSDKSetupWeChatByAppId:@"wx7d4ad828c888007b"
                                       appSecret:@"ef33a8fead12b13d5e649393ff982c9e"];
                 break;
             case SSDKPlatformTypeQQ:
                 [appInfo SSDKSetupQQByAppId:@"1105487827"
                                      appKey:@"KEYmnKoalfkRubvi40l"
                                    authType:SSDKAuthTypeBoth];
                 break;
             default:
                 break;
         }
    }];
}

- (void)checkNet
{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        [self testt];
         //[self performSelector:@selector(testt) withObject:nil afterDelay:1];
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: {
                NSLog(@"AFNetworkReachabilityStatusUnknown");
                break;
            }
            case AFNetworkReachabilityStatusNotReachable: {

                NSLog(@"AFNetworkReachabilityStatusNotReachable");
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWWAN: {
                NSLog(@"AFNetworkReachabilityStatusReachableViaWWAN");
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWiFi: {
            
                NSLog(@"AFNetworkReachabilityStatusReachableViaWiFi");
                break;
            }
            default: {
                break;
            }
                
        }
    }];

}

- (void)testt
{
    
    [MyCar isBus:^(bool isbus) {
        
        NSLog(@"%@",ISBUS);
        NSLog(@"%d",isbus);
        if ([ISBUS boolValue] == isbus) {
            return;
        }
        if (isbus) {
            [[NSUserDefaults standardUserDefaults]setObject:@(1) forKey:@"isbus"];
            [self contactNet];
        }else
        {
            [[NSUserDefaults standardUserDefaults]setObject:@(0) forKey:@"isbus"];
        }
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"网络发生变化" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//        [alert show];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"网络发生变化" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [[NSUserDefaults standardUserDefaults]setObject:@(1) forKey:@"showad"];
            
            MyTabBarController *tab = [[MyTabBarController alloc]initWithDic:nil];
            self.window.rootViewController = tab;
        }]];
        
//        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        UIViewController *vc = [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
        [vc presentViewController:alert animated:YES completion:nil];
    }];
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
 
    if (alertView.tag == 1000) {
    //推送弹窗
        switch (buttonIndex) {
            case 0:{
                
                NSLog(@"忽略");
                
                break;
            }
            case 1:{
                
                NSLog(@"查看");
                
                HomeDetailViewController *detail = [[HomeDetailViewController alloc]init];
                
                UIViewController *vc = [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
                detail.urlstr = [_userinfo objectForKey:@"url"];
                [vc.navigationController pushViewController:detail animated:YES];
                
                break;
            }
            default:{
                break;
            }
        }
    
    }else{
    //网络弹窗
    switch (buttonIndex) {
        case 0:
        {
            [[NSUserDefaults standardUserDefaults]setObject:@(1) forKey:@"showad"];
            
            MyTabBarController *tab = [[MyTabBarController alloc]initWithDic:nil];
            self.window.rootViewController = tab;
            
            break;
        }
        default:
            break;
    }
    }
}

- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController* tabBarController = (UITabBarController*)rootViewController;
        return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* nav = (UINavigationController*)rootViewController;
        return [self topViewControllerWithRootViewController:nav.visibleViewController];
    } else if (rootViewController.presentedViewController) {
        UIViewController* presentedViewController = rootViewController.presentedViewController;
        return [self topViewControllerWithRootViewController:presentedViewController];
    } else {
        return rootViewController;
    }
}


- (void)registUMeng:(NSDictionary *)launchOptions
{
    [MobClick startWithAppkey:@"56989fe467e58eabf1001978" reportPolicy:BATCH channelId:nil];
    
    [UMessage startWithAppkey:@"56989fe467e58eabf1001978" launchOptions:launchOptions];
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        UIUserNotificationSettings *userSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert
                                                                        categories:nil];
        [UMessage registerRemoteNotificationAndUserNotificationSettings:userSettings];
    }
//    [UMessage getTags:^(NSSet *responseTags, NSInteger remain, NSError *error) {
//        
//        NSLog(@"%@",responseTags);
//    }];
//    [UMessage addTag:@"1" response:^(id responseObject, NSInteger remain, NSError *error) {
//       
//        NSLog(@"%@",responseObject);
//    }];
    
    [UMessage setLogEnabled:NO];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [[NSUserDefaults standardUserDefaults]setObject:deviceToken forKey:@"deviceToken"];
    NSLog(@"%@",[[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                  stringByReplacingOccurrencesOfString: @">" withString: @""]
                 stringByReplacingOccurrencesOfString: @" " withString: @""]);
    if ([SHOULDREMOTE boolValue]) {
        
        [UMessage registerDeviceToken:deviceToken];
    }
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    //如果注册不成功，打印错误信息，可以在网上找到对应的解决方案
    //如果注册成功，可以删掉这个方法
    NSLog(@"application:didFailToRegisterForRemoteNotificationsWithError: %@", error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    //关闭友盟自带的弹出框
    [UMessage setAutoAlert:NO];
    
    [UMessage didReceiveRemoteNotification:userInfo];
    
    
    //    self.userInfo = userInfo;
    //    //定制自定的的弹出框
        if([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
        {
            [self showInfo:userInfo];
        }else{
            
//            HomeDetailViewController *detail = [[HomeDetailViewController alloc]init];
//            detail.urlstr = [userInfo objectForKey:@"url"];
//            UIViewController *vc = [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
//            
//            [vc.navigationController pushViewController:detail animated:YES];
        }
}

- (void)showInfo:(NSDictionary *)userInfo
{
    _userinfo = userInfo;
    UIViewController *vc = [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:[[userInfo objectForKey:@"aps"] objectForKey:@"alert"] message:[userInfo objectForKey:@"b"] preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSLog(@"查看");
        
        HomeDetailViewController *detail = [[HomeDetailViewController alloc]init];
        detail.urlstr = [_userinfo objectForKey:@"url"];
        [vc.navigationController pushViewController:detail animated:YES];
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [vc presentViewController:alert animated:YES completion:nil];
    
//    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]
//                                                        message:[userInfo objectForKey:@"b"]
//                                                       delegate:self
//                                              cancelButtonTitle:@"忽略"
//                                              otherButtonTitles:@"查看",nil];
//    
//    alertView.tag = 1000;
//    [alertView show];
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
    [UMessage setAutoAlert:NO];
    
    [UMessage didReceiveRemoteNotification:userInfo];
    
    if([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
    {
        [self showInfo:userInfo];
    }else{
        
                    HomeDetailViewController *detail = [[HomeDetailViewController alloc]init];
                    detail.urlstr = [userInfo objectForKey:@"url"];
                    UIViewController *vc = [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
        
                    [vc.navigationController pushViewController:detail animated:YES];
    }
    
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    NSLog(@"resignactive");
    
    [[MyAd sharedMyad]post];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"endcollect" object:nil];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    NSLog(@"DidEnterBackground");
//    [[UIApplication sharedApplication]beginBackgroundTaskWithExpirationHandler:^(){
//        
//        NSLog(@"程序关闭");
//        [UMessage removeTag:@"1" response:^(id responseObject, NSInteger remain, NSError *error) {
//            
//            NSLog(@"%@",responseObject);
//        }];
//    }];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.isFull = NO;
    [self checkNet];
    
    NSLog(@"WillEnterForeground");
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    NSLog(@"DidBecomeActive");
    [[NSNotificationCenter defaultCenter]postNotificationName:@"startcollect" object:nil];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
   NSLog(@"WillTerminate");
    
}
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    if (_isFull) {
        return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight;
    } else {
        return UIInterfaceOrientationMaskPortrait;
    }
}

@end
